<template>
  <el-dialog title="推流" :visible.sync="liveVisible" width="50%">
    <div>
      <h1>屏幕共享与截图示例</h1>
      <button @click="startScreenShare">开始屏幕共享</button>
      <button @click="stopScreenShare" :disabled="!isSharing">停止屏幕共享</button>
      <button @click="captureScreenshot" :disabled="!isSharing">截图</button>
      <video ref="screenVideo" autoplay playsinline style="width: 100%; height: auto; border: 1px solid #ddd;"></video>
      <div v-if="screenshot">
        <h2>截图结果：</h2>
        <img :src="screenshot" alt="截图" style="max-width: 100%; border: 1px solid #ddd;" />
      </div>
      <div style="margin: 10px 0;">
        <el-input placeholder="请输入webRtc推流地址" v-model="liveParam.obsServer"></el-input>
      </div>
      <div id="id_local_video" style="width:780px;height:450px;border:1px solid blue; float: left; margin: 10px;"></div>
      <el-button type="primary" @click="submit">开始推流</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getLive } from '../../api/table.js'
export default {
  data() {
    return {
      isSharing: false, // 是否正在共享屏幕
      mediaStream: null, // 媒体流对象
      screenshot: null, // 截图的 base64 数据
      liveVisible: false,
      liveParam: {},
      livePusher: null
      // videoEffectManager: null
    }
  },
  created() {
    this.readyPusher()
  },
  methods: {
    //初始化腾讯推流组件
    readyPusher() {
      // eslint-disable-next-line no-undef
      this.livePusher = new TXLivePusher()
      // 指定本地视频播放器容器：
      this.livePusher.setRenderView('id_local_video')
      // 设置视频质量
      this.livePusher.setVideoQuality('720p')
      // 设置音频质量
      this.livePusher.setAudioQuality('standard')
      // 自定义设置帧率
      this.livePusher.setProperty('setVideoFPS', 25)
      console.log('readyPusher OK', this.livePusher)
    },
    openDialog(row) {
      getLive({
        tournamentId: row.id,
        endTime: this.getFormattedDatePlusOneDay(),
        type: 2
      }).then(res => {
        console.log('res', res)
        if (res.code == 200) {
          this.liveParam = res.data
          this.liveVisible = true
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 当前时间加1天
    getFormattedDatePlusOneDay() {
      const now = new Date()
      now.setDate(now.getDate() + 1) // 增加1天
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要+1
      const date = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`
    },
    submit() {
      let that = this
      let livePusher = this.livePusher
      //  'webrtc://pushlive.yundongshugenlive.cn/live/185qVSD8p?txSecret=c845b2962df69caa1fdabcc4759a4b80&txTime=677BC619'
      Promise.all([livePusher.startScreenCapture(), livePusher.startMicrophone()])
        .then(function() {
          //传入的是一个推流地址，后端返回的，把后端返回的一个地址前边的rtmp换成webrtc就可以了
          livePusher
            .startPush(that.liveParam.obsServer)
            .then(() => {
              console.log('pushing成功1')
              if (livePusher.isPushing()) {
                console.log('pushing222')
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(err => {
          console.log(err)
        })
    },
    //
    async startScreenShare() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
        alert('当前浏览器不支持屏幕共享功能。请使用最新版本的谷歌浏览器。')
        return
      }

      try {
        // 调用 getDisplayMedia 获取屏幕媒体流
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: {
            cursor: 'always' // 是否显示鼠标指针
          },
          audio: false // 是否捕获音频
        })

        this.mediaStream = stream
        this.isSharing = true

        // 将媒体流绑定到 <video> 元素
        const videoElement = this.$refs.screenVideo
        if (videoElement) {
          videoElement.srcObject = stream
        }

        // 监听屏幕共享停止事件
        stream.getVideoTracks()[0].addEventListener('ended', () => {
          this.stopScreenShare()
        })
      } catch (error) {
        console.error('屏幕共享失败:', error)
        alert('屏幕共享失败，请检查权限设置。')
      }
    },
    stopScreenShare() {
      if (this.mediaStream) {
        // 停止所有媒体流轨道
        this.mediaStream.getTracks().forEach(track => track.stop())
        this.mediaStream = null
      }
      this.isSharing = false

      // 停止视频播放
      const videoElement = this.$refs.screenVideo
      if (videoElement) {
        videoElement.srcObject = null
      }
    },
    captureScreenshot() {
      if (!this.isSharing) {
        alert('请先开始屏幕共享！')
        return
      }

      const videoElement = this.$refs.screenVideo
      if (!videoElement) {
        alert('视频元素未找到！')
        return
      }

      // 创建一个 canvas，用于绘制视频帧
      const canvas = document.createElement('canvas')
      canvas.width = videoElement.videoWidth
      canvas.height = videoElement.videoHeight

      const context = canvas.getContext('2d')
      context.drawImage(videoElement, 0, 0, canvas.width, canvas.height)

      // 生成 base64 图片数据
      this.screenshot = canvas.toDataURL('image/png')

      // 可选：下载截图
      this.downloadImage(this.screenshot, 'screenshot.png')
    },
    downloadImage(dataUrl, fileName) {
      const link = document.createElement('a')
      link.href = dataUrl
      link.download = fileName
      link.click()
    }
  }
}
</script>

<style>
button {
  margin: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}
</style>
